import type { Router } from 'vue-router'
import { useAuthStore } from "@/store";

export function setupPageGuard(router: Router) {
  const whiteRoutes = ["/user/login", "/user/register"]

  router.beforeEach((to, from, next) => {
    const authStore = useAuthStore()

    if (!authStore.token && !authStore.authorizationToken) {
      try {
        if (to.path !== '/user/login' && whiteRoutes.indexOf(to.path) < 0)
          next({ name: 'login' })
        else next()
      } catch (error) {
        if (to.path !== '/500') next({ name: '500' })
        else next()
      }
    } else {
      next()
    }
  })
}
